#include<iostream>
#include"../comm/httplib.h"
#include"oj_control.hpp"
#include<signal.h>
using namespace httplib;
using namespace ns_control;
void Usage(std::string proc)
{
    std::cerr<<"Usage:"<<"\n\t"<<proc<<" port"<<std::endl;
}
/// @brief 
/// @param argc 
/// @param argv 
/// @return 
static Control *_ctrol=nullptr;
void Recorver(int signo)
{
    _ctrol->RecoverMachine();
}

int main(int argc,char*argv[])
{
    signal(SIGQUIT,Recorver);
    //aaa::vector<int> v;
    if(argc!=2)
    {
        Usage(argv[0]);
        return 1;
    }
    //用户请求的路由功能
    Server svr;
    Control control;
    _ctrol=&control;
    //获取所有题目列表
     svr.Get("/all_questions",[&control](const Request &req,Response &resp){
        //返回一张包含所有题目的网页
        std::string html;
        control.AllQuestions(&html);
        resp.set_content(html,"text/html;charset=utf-8");
    });

    //获取指定题目
    // /question/100->正则匹配
    //R"()"可以避免字符串转义
     svr.Get(R"(/question/(\d+))",[&control](const Request &req,Response &resp){
        std::string number=req.matches[1];
        std::string html;
        control.Question(number,&html);
        resp.set_content(html,"text/html;charset=utf-8");
    });
    //用户提交代码，进行判题（1.测试完成用例 2.编译运行）
     svr.Post(R"(/judge/(\d+))",[&control](const Request &req,Response &resp){
        std::string number=req.matches[1];
        std::string res_json;
        control.judge(number,req.body,&res_json);
        resp.set_content(res_json,"application/json;charset=utf-8");
       //resp.set_content("指定判题："+number,"text/plain;charset=utf-8");
    });
    svr.set_base_dir("./wwwroot");
    svr.listen("0.0.0.0",atoi(argv[1]));
    return 0;
}